package com.fzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.model.param.personal.UpdateCurrentUserNameAndNickNameParam;
import com.fzg.common.tool.JwtUtil;
import com.fzg.entity.*;
import com.fzg.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.time.ZoneId;
import java.util.*;

/**
 * create by fzg
 * 2022/6/20 13:55
 */

@Service
public class PersonalService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DiaryMapper diaryMapper;

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private UserGuanzhuMapper userGuanzhuMapper;

    /**
     * 检验token是否过期
     * @return ResponseWrapper
     */
    public ResponseWrapper getLoginUserInfoByToken(String token){
        User user = userMapper.selectById(JwtUtil.getTokenId(token));
        HashMap<String, Object> map = new HashMap<>();
        if (user != null){
            // 博客数量
            Long blogCount = blogMapper.selectCount(new LambdaQueryWrapper<Blog>().eq(Blog::getUserAid, user.getAid()));
            map.put("blogCount",blogCount);
            // 日记数量
            Long diaryCount = diaryMapper.selectCount(new LambdaQueryWrapper<Diary>().eq(Diary::getUserAid, user.getAid()));
            map.put("diaryCount",diaryCount);

            // 用户aid
            map.put("currentUserAid", user.getAid());

            // 当前登录用户关注了多少用户
            map.put("userConcern",
                    userGuanzhuMapper.selectCount(new LambdaQueryWrapper<UserGuanzhu>()
                            .eq(UserGuanzhu::getGuanzhuUserAid,user.getAid())
                    ));

            // 当前登陆的用户被多少其他用户关注
            map.put("userConcerned",
                    userGuanzhuMapper.selectCount(new LambdaQueryWrapper<UserGuanzhu>()
                            .eq(UserGuanzhu::getBeiguanzhuUserAid,user.getAid())
                    ));

            // 用户名
            map.put("userName",user.getUserName());

            // 昵称
            map.put("nickName",user.getNickName());

            // 用户头像
            map.put("avatar",user.getAvatar() == null ? "https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg" : user.getAvatar());

            // 用户个人中心背景图
            map.put("backImage",user.getBackImage() == null ? "https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/user/avatar_userbg/more-leaves.png" : user.getBackImage());

            if (user.getCreateTime() != null){
                Date createTime = Date.from(user.getCreateTime().atZone(ZoneId.systemDefault()).toInstant());
                long time = createTime.getTime();
                long time1 = new Date().getTime();
                long dayCount = (time1-time)/1000/60/60/24;
                map.put("dayCount",dayCount);
            }else {
                map.put("dayCount",0);
            }


            // 用户标签
            ArrayList<String> userTag = new ArrayList<>();
            List<Tag> tagList = tagMapper.selectList(new LambdaQueryWrapper<Tag>()
                    .orderByDesc(Tag::getAid)
                    .eq(Tag::getUserAid, user.getAid()));
            for (Tag tag : tagList) {
                userTag.add(tag.getName());
            }
            map.put("userTag",userTag);
            return ResponseWrapper.markSuccess(map);
        }else {
            return ResponseWrapper.markError();
        }
    }

    /**
     * 更新当前用户的头像
     * @return ResponseWrapper
     */
    public ResponseWrapper updateUserAvatar(HttpServletRequest request, String avatarUrl){
        // 得到当前用户
        User user = userMapper.selectById(JwtUtil.getTokenId(request.getHeader("token")));
        user.setAvatar(avatarUrl);
        int updateById = userMapper.updateById(user);
        if (updateById > 0){
            return ResponseWrapper.markCustomSuccess("上传成功！");
        }else {
            return ResponseWrapper.markCustomError("上传失败！");
        }
    }


    /**
     * 更新当前用户的背景
     * @return ResponseWrapper
     */
    public ResponseWrapper updateUserBg(HttpServletRequest request,String bgUrl){
        // 得到当前用户
        User user = userMapper.selectById(JwtUtil.getTokenId(request.getHeader("token")));
        user.setBackImage(bgUrl);
        int updateById = userMapper.updateById(user);
        if (updateById > 0){
            return ResponseWrapper.markCustomSuccess("上传成功！");
        }else {
            return ResponseWrapper.markCustomError("上传失败！");
        }
    }


    /**
     * 查询是否有相同的用户名
     * @return ResponseWrapper
     */
    public ResponseWrapper isSimpleUserName(HttpServletRequest request, String userName){

        // 查询当前登陆用户的aid
        Integer currentUserAid = JwtUtil.getTokenId(request.getHeader("token"));

        List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, userName)
                .ne(User::getAid, currentUserAid)
        );

        if (users.size() > 0){
            return ResponseWrapper.markSuccess(true);
        }else {
            return ResponseWrapper.markSuccess(false);
        }
    }


    /**
     * 更新当前登陆用户的用户名和昵称
     * @return ResponseWrapper
     */
    public ResponseWrapper updateCurrentUserNameAndNickName(HttpServletRequest request, UpdateCurrentUserNameAndNickNameParam param){

        // 查询当前登陆用户的aid
        Integer currentUserAid = JwtUtil.getTokenId(request.getHeader("token"));

        // 当前登陆的用户
        User user = userMapper.selectById(currentUserAid);
        user.setUserName(param.getUserName());
        user.setNickName(param.getNickName());

        int updateById = userMapper.updateById(user);
        if (updateById > 0){
            return ResponseWrapper.markCustomSuccess("更新成功！");
        }else {
            return ResponseWrapper.markCustomError("失败了！请稍后再试！");
        }
    }

    /**
     * 获取轮播图的内容
     * @return ResponseWrapper
     */
    public ResponseWrapper getSwiperContent(){
        // 三个日记
        List<Diary> diaries = diaryMapper.selectList(new LambdaQueryWrapper<Diary>().orderByDesc(Diary::getCreateTime));
        ArrayList<Object> result = new ArrayList<>();

        for (Diary diary : diaries.subList(0,3)) {
            HashMap<String, Object> item = new HashMap<>();
            item.put("type","diary");
            item.put("id",diary.getAid());
            // 日记图片有很多张或者没有或者只有 一张
            if (diary.getDiaryImgUrl() == null){  // 如果该日记没有图片
                item.put("url","https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1113%2F052420110515%2F200524110515-11-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1658383473&t=2afc825ebaf15cf0c11775764902135c");
            }else {
                boolean flag = false;
                for (int i = 0; i < diary.getDiaryImgUrl().length(); i++) {
                    String ch = String.valueOf(diary.getDiaryImgUrl().charAt(i));
                    if (ch.equals(";")) {
                        flag = true;
                        break;
                    }
                }
                if (flag){ // 说明有两张及两张以上的图片
                    String[] picUrls = diary.getDiaryImgUrl().split(";");
                    item.put("url",picUrls[0]);
                }else { // 说明只有一张
                    item.put("url",diary.getDiaryImgUrl());
                }
            }
            result.add(item);
        }

        // 三个博客
        List<Blog> blogs = blogMapper.selectList(new LambdaQueryWrapper<Blog>().orderByDesc(Blog::getCreateTime));
        for (Blog blog : blogs.subList(0,3)) {
            HashMap<String, Object> item = new HashMap<>();
            item.put("type","blog");
            item.put("id",blog.getAid());
            // 博客图片有很多张或者没有或者只有 一张
            if (blog.getBlogImgurl() == null){  // 如果该博客没有图片
                item.put("url","https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1113%2F052420110515%2F200524110515-11-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1658383473&t=2afc825ebaf15cf0c11775764902135c");
            }else {
                boolean flag = false;
                for (int i = 0; i < blog.getBlogImgurl().length(); i++) {
                    String ch = String.valueOf(blog.getBlogImgurl().charAt(i));
                    if (ch.equals(";")) {
                        flag = true;
                        break;
                    }
                }
                if (flag){ // 说明有两张及两张以上的图片
                    String[] picUrls = blog.getBlogImgurl().split(";");
                    item.put("url",picUrls[0]);
                }else { // 说明只有一张
                    item.put("url",blog.getBlogImgurl());
                }
            }
            result.add(item);
        }
        // 将result里面的每一项随机打乱顺序
        Collections.shuffle(result);

        return ResponseWrapper.markSuccess(result);
    }

}
